import org.mortbay.util.ajax.JSON;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Hive操作类
 *
 * @author Ace Lee
 * @date 2019/8/27 14:18
 * @version 1.0
 **/
public class HiveClientUtils {

    private static String driverName = "com.cloudera.hive.jdbc4.HS2Driver";

    //填写hive的IP，之前在配置文件中配置的IP
    private static String Url = "jdbc:hive2://10.10.10.10:10000/hbzfw";

    private static Connection conn;

    private static PreparedStatement ps;

    private static ResultSet rs;

    //创建连接
    public static Connection getConnnection() {
        try {
            Class.forName(driverName);
            //此处的用户名一定是有权限操作HDFS的用户，否则程序会提示"permission deny"异常
            conn = DriverManager.getConnection(Url, "", "");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            System.exit(1);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    public static PreparedStatement prepare(Connection conn, String sql) {
        PreparedStatement ps = null;
        try {
            ps = conn.prepareStatement(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return ps;
    }

    public static List<Map<String,Object>> getResult(String sql) {
        List<Map<String,Object>> rowDatas = new ArrayList<Map<String, Object>>();
        System.out.println(sql);
        conn = getConnnection();

        try {
            ps = prepare(conn, sql);
            rs = ps.executeQuery();
            ResultSetMetaData md = rs.getMetaData();
            int columCount = md.getColumnCount();

            while(rs.next()) {
                Map<String,Object> rowData = new HashMap<String, Object>();
                for(int i = 1; i <= columCount; i++) {
                    rowData.put(md.getColumnName(i), rs.getObject(i));
                }
                rowDatas.add(rowData);
            }
            System.out.println(JSON.toString(rowDatas));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rowDatas;
    }

}